<?php
require_once "cw2conf.php";
include_once "misc.php";

echo "POST:";
var_dump($_POST);
//echo "COOKIE:";
//var_dump($_COOKIE);

$tournament_id = 0;
$logged_player_id = CW2_NO_OBJECT;
$logged_tplayer_id = CW2_NO_OBJECT;
$logged_tgroup_id = CW2_NO_OBJECT;
$logged_permissions = 0;

if (IsSet($_POST['main_tournament_id']))
{
 $tournament_id = IntVal($_POST['main_tournament_id']);
}

if (IsSet($_POST['main_player_id']))
{
 $logged_player_id = IntVal($_POST['main_player_id']);
}

$dbl=DBConn();

if (GetTournament($tournament_id)<0) {echo "!!no tournament";return;}
if (GetTournamentPlayers($tournament_id)<0) {echo "!!no tournament players";return;}

echo "TOURNAMENT:";
var_dump($tournament);
echo "PLAYERS:";
var_dump($tplayers);

$orders = array();

foreach ($_POST['order_jsid'] as $i => $order_jsid)
{
 $order_id = IntVal($_POST['order_id'][$i]);
 $order_type = IntVal($_POST['order_type'][$i]);
 $tournament_id = IntVal($_POST['tournament_id'][$i]);
 $turn = IntVal($_POST['turn'][$i]);
 $destination_id = IntVal($_POST['destination_id'][$i]);
 $tplayer_id = IntVal($_POST['tplayer_id'][$i]);
 $tgroup_id = IntVal($_POST['tgroup_id'][$i]);
 $unit_id = IntVal($_POST['unit_id'][$i]);
 $comment = $_POST['unit_id'][$i];
 
 $order = array('order_jsid' => $order_jsid, 'order_id' => $order_id, 'order_type' => $order_type, 'tournament_id' => $tournament_id,
 'turn' => $turn, 'destination_id' => $destination_id, 'tplayer_id' => $tplayer_id, 'tgroup_id' => $tgroup_id, 'unit_id' => $unit_id,
 'comment' => $comment);
 CheckOrder($order, 1, 0);
 
 if ($order['status'] == CW2_ACCEPTED)
 {
  if ($order['replace'])
  {
   $sql_action_txt = "Update order $order_id";
   $sql = "UPDATE cw2_orders SET ";
   $sql_where = "WHERE order_id='$order_id';";
  }
  else
  {
   $sql_action_txt = "Insert new order";
   $sql = "INSERT INTO cw2_orders SET tournament_id = '".$order['tournament_id']."', turn = '".$order['turn']."', ";
   $sql_where = ";";
  }
  
  $sql.= "order_type = '".$order['order_type']."', tplayer_id = '".$order['tplayer_id']."', tgroup_id = '".$order['tgroup_id']."', unit_id = '".$order['unit_id']."', destination_id = '".$order['destination_id']."', comment = '".mysql_real_escape_string($order['comment'], $dbl) . "'";
  $sql.= $sql_where;
 
  if (!mysql_query($sql, $dbl))
  {
   fecho($sql_action_txt." - query ", $sql, " failed : ", mysql_error());
   $order['status'] += CW2_SQL_ERROR;
   $order['status_message'] = $GLOBALS['lang_cw2_order_status'][CW2_SQL_ERROR];
  }
  else if (!$order['replace'])
  {
   $order['order_id'] = mysql_insert_id($dbl);
  }
 }

 echo "<br>
  ".$order['status_message'];
 
 $orders[$i] = $order;
}

?>